package com.czy.daishusys.ui;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;

import com.czy.daishusys.R;
import com.czy.daishusys.entity.generator.DataGenerator;
import com.czy.daishusys.global.Constants;
import com.czy.daishusys.rxbus.RxBus;
import com.czy.daishusys.rxbus.Subscribe;
import com.czy.daishusys.rxbus.ThreadMode;
import com.czy.daishusys.utils.MyLog;
import com.czy.daishusys.utils.PhoneUtils;
import com.czy.daishusys.utils.tiputils.MToast;
import com.easemob.cases.MessageHelper;
import com.hyphenate.EMGroupChangeListener;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMVoiceMessageBody;

import java.util.List;

import butterknife.BindView;
import q.rorbin.badgeview.Badge;
import q.rorbin.badgeview.QBadgeView;

public class MainActivity extends BaseActivity implements TabHost.OnTabChangeListener {
    private Fragment[] mFragments;
    private FragmentTabHost mTabHost;
    private Badge badge;
    //    当前选中的views的下标
    private int currentIndex = 0;
    private long exitTime = 0;
    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_main;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        RxBus.getDefault().register(this);
        mFragments = DataGenerator.getFragments();
        mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        // 关联TabHost
        mTabHost.setup(this, getSupportFragmentManager(), R.id.home_container);
        //注意，监听要设置在添加Tab之前
        mTabHost.setOnTabChangedListener(this);

        //添加Tab
        for (int i = 0; i < 3; i++) {
            //生成TabSpec
            TabHost.TabSpec tabSpec = mTabHost.newTabSpec(DataGenerator.mTabTitle[i]).setIndicator(DataGenerator.getTabView(this, i));
            // 添加Tab 到TabHost，并绑定Fragment
            Bundle bundle = new Bundle();
//            bundle.putString("from", "FragmentTabHost Tab");
            mTabHost.addTab(tabSpec, mFragments[i].getClass(), bundle);
        }


        //去掉Tab 之间的分割线
        mTabHost.getTabWidget().setDividerDrawable(null);
        mTabHost.setCurrentTab(0);
        badge = new QBadgeView(this).bindTarget(mTabHost.getTabWidget().getChildTabViewAt(1)).setBadgeNumber(0).setGravityOffset(30, 0, true)
                .setBadgePadding(2, true).setBadgeBackgroundColor(ContextCompat.getColor(this, R.color.appThemeNewsColor)).setOnDragStateChangedListener(new Badge.OnDragStateChangedListener() {
                    @Override
                    public void onDragStateChanged(int dragState, Badge badge, View targetView) {
                        if (dragState == STATE_SUCCEED) {
                            EMClient.getInstance().chatManager().markAllConversationsAsRead();
                            refreshUIWithMessage();
                        }
                    }
                });
        updateUnreadLabel();
        EMClient.getInstance().chatManager().addMessageListener(messageListener);
        EMClient.getInstance().groupManager().addGroupChangeListener(groupChangeListener);

    }

    @Override
    protected void updateViews() {

    }

    @Override
    public void onTabChanged(String tabId) {
        updateTabState();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unRegister(this);
    }

    @Subscribe(code = Constants.RXBUS_CODE_READ_MESSAGE, threadMode = ThreadMode.MAIN)
    public void refresh(String event) {
        Log.i("King", "RXBUS_CODE_REFRESH_MESSAGE:");

    }

    EMMessageListener messageListener = new EMMessageListener() {

        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            // notify new message
            /*for (EMMessage message : messages) {
                MessageHelper.getInstance().getNotifier().onNewMsg(message);
            }*/
            for (EMMessage emMessage : messages) {
                MyLog.e("hep", "收到消息" + emMessage.getStringAttribute(MessageHelper.MESSAGE_EXT_DATA, null));
                MyLog.e("hep", "收到消息" + emMessage.getStringAttribute(MessageHelper.MESSAGE_EXT_CUSTOM_TYPE, null));
            }
            refreshUIWithMessage();
            MyLog.e("hep", "收到消息");
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {
            //red packet code : 处理红包回执透传消息
            /*for (EMMessage message : messages) {
                EMCmdMessageBody cmdMsgBody = (EMCmdMessageBody) message.getBody();
                final String action = cmdMsgBody.action();//获取自定义action
                if (action.equals(RedPacketConstant.REFRESH_GROUP_RED_PACKET_ACTION)) {
                    RedPacketUtil.receiveRedPacketAckMessage(message);
                }
            }*/
            //end of red packet code
            refreshUIWithMessage();
            MyLog.e("hep", "透传消息");
        }

        @Override
        public void onMessageRead(List<EMMessage> messages) {

            MyLog.e("hep", "已读回执");
        }

        @Override
        public void onMessageDelivered(List<EMMessage> message) {
            MyLog.e("hep", "已送达回执");
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
            MyLog.e("hep", "消息状态变动");
        }
    };
    EMGroupChangeListener groupChangeListener = new EMGroupChangeListener() {
        @Override
        public void onInvitationReceived(String s, String s1, String s2, String s3) {

        }

        @Override
        public void onRequestToJoinReceived(String s, String s1, String s2, String s3) {

        }

        @Override
        public void onRequestToJoinAccepted(String s, String s1, String s2) {

        }

        @Override
        public void onRequestToJoinDeclined(String s, String s1, String s2, String s3) {

        }

        @Override
        public void onInvitationAccepted(String s, String s1, String s2) {

        }

        @Override
        public void onInvitationDeclined(String s, String s1, String s2) {

        }

        @Override
        public void onUserRemoved(String s, String s1) {

        }

        @Override
        public void onGroupDestroyed(String s, String s1) {
            refreshUIWithMessage();
        }

        @Override
        public void onAutoAcceptInvitationFromGroup(String s, String s1, String s2) {

        }
    };


    private void refreshUIWithMessage() {
        runOnUiThread(new Runnable() {
            public void run() {
                // refresh unread count
                updateUnreadLabel();
                if (currentIndex == 1) {
                    // refresh conversation list
                    RxBus.getDefault().post(Constants.RXBUS_CODE_REFRESH_MESSAGE, "refresh");
                }
            }
        });
    }

    /**
     * update unread message count
     */
    public void updateUnreadLabel() {
        if (badge != null) {
            badge.setBadgeNumber(getUnreadMsgCountTotal());
        }
    }

    /**
     * get unread message count
     *
     * @return
     */
    public int getUnreadMsgCountTotal() {
        int unreadMsgCountTotal = 0;
        unreadMsgCountTotal = EMClient.getInstance().chatManager().getUnreadMessageCount();
        return unreadMsgCountTotal;
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateUnreadLabel();
    }

    public void swichTab(int tabId) {
        mTabHost.setCurrentTab(tabId);
    }

    /**
     * 更新Tab 的状态
     */
    private void updateTabState() {
        TabWidget tabWidget = mTabHost.getTabWidget();
        for (int i = 0; i < tabWidget.getTabCount(); i++) {
            View view = tabWidget.getChildTabViewAt(i);
            ImageView tabIcon = (ImageView) view.findViewById(R.id.tab_image);
            TextView tabText = (TextView) view.findViewById(R.id.tab_title);
            if (i == mTabHost.getCurrentTab()) {
                currentIndex = i;
                tabIcon.setImageResource(DataGenerator.mTabResPressed[i]);
                tabText.setTextColor(getResources().getColor(R.color.appThemeColor));
            } else {
                tabIcon.setImageResource(DataGenerator.mTabRes[i]);
                tabText.setTextColor(getResources().getColor(R.color.appThemeTitleColor));
            }
        }
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                PhoneUtils.ShowToastMessage(MainActivity.this, getString(R.string.key_back_tips));
                exitTime = System.currentTimeMillis();
            } else {
                finish();

            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
